    //
    //  XOClubViewController.m
    //  didigo
    //
    //  Created by JS_Coder on 2019/2/18.
    //  Copyright © 2019 lifayu. All rights reserved.
    //

#import "XOClubViewController.h"
#import "XOClubMessageCell.h"
#import "XOClubPublishController.h"
#import "EJSClubListRequest.h"
#import "EJSCLubListModel.h"
#import "EJSClubMessageModel.h"
#import "ManShiGuang-Swift.h"
#import "XOClubImageViewController.h"
#import "XOClubViewModel.h"
#import "XOClubCommentViewController.h"
#import "EJSClublikeRequest.h"
#import "XOLikeButton.h"
#import "EJSClubCancelLikeRequest.h"
#import <SVProgressHUD.h>
@interface XOClubViewController ()<UITableViewDelegate, UITableViewDataSource, XOClubImageViewProtocol, UIScrollViewDelegate>
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property(nonatomic, strong)  EJSClubListModel* clubList;
StrongProperty NSIndexPath *updateIndexPath;
StrongProperty UIImageView *imageView;
StrongProperty UIView *imageBaseView;
StrongProperty XOLikeButton *updateLikeButton;
@end

@implementation XOClubViewController

- (void)viewDidLoad {
    [super viewDidLoad];
        // Do any additional setup after loading the view.
    [self getClubListRequest];
    [[NSNotificationCenter defaultCenter]addObserverForName:@"canUpdateClub" object:nil queue:nil usingBlock:^(NSNotification * _Nonnull note) {
        [self.tableView.mj_header beginRefreshing];
    }];
    [[NSNotificationCenter defaultCenter]addObserverForName:@"updateClubList" object:nil queue:nil usingBlock:^(NSNotification * _Nonnull note) {
        [XOClubViewModel shared].isComment = NO;
        [self getClubListRequest];
    }];
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)setClubList:(EJSClubListModel *)clubList {
    _clubList = clubList;
    for (EJSClubMessageModel *model in clubList.list) {
        CGFloat height = model.rowHeight;
    }
}

- (void)configOwnViews {
    self.title = @"圈子";
    [self configNavigationRightItmeWithTitle:@"发布" titleColor: AppTextColor font:CHINESE_PingFangRegular(15)];
    [self.tableView registerNib:[UINib nibWithNibName:@"XOClubMessageCell" bundle:nil] forCellReuseIdentifier:@"XOClubMessageCell"];
    [self.tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    self.tableView.estimatedRowHeight = 0;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        self.updateIndexPath = NULL;
        self.updateLikeButton = NULL;
        [self getClubListRequest];
    }];
}

- (void)rightBarButtonAction:(id)sender {
    NSLog(@"发布");
    ShowAlbumPhotos * publishVc = [[ShowAlbumPhotos alloc]init];
    [self.navigationController pushViewController:publishVc animated:YES];
}

#pragma Get Club List
- (void)getClubListRequest {
    FlyWeakSelf
    [SVProgressHUD show];
    EJSClubListRequest *request = [EJSClubListRequest new];
    [request asyncRequestWithsuccessHandler:^(BaseResponse *response) {
        [weakSelf.tableView.mj_header endRefreshing];
        [SVProgressHUD dismiss];
        EJSClubListModel *model = response.data;
        weakSelf.clubList = model;
        if (weakSelf.updateIndexPath && weakSelf.updateLikeButton) {
            [weakSelf.tableView reloadRowsAtIndexPaths:@[weakSelf.updateIndexPath] withRowAnimation:UITableViewRowAnimationFade];
        }else {
            [weakSelf.tableView reloadData];
        }
    } failHandler:^(BaseResponse *response) {
        [weakSelf.tableView.mj_header endRefreshing];
        [SVProgressHUD dismiss];
    }];
}
#pragma TableViewDelegate


#pragma TableViewDataSource
    //MARK: - TableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.clubList.list.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    XOClubMessageCell* cell = [tableView dequeueReusableCellWithIdentifier:@"XOClubMessageCell" forIndexPath:indexPath];
    cell.messageModel = self.clubList.list[indexPath.row];
    cell.delegate = self;
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    EJSClubMessageModel *model = self.clubList.list[indexPath.row];
    return model.rowHeight;
}

    //MARK: - CLUB MESSAGE CELL DELEGATE <SHOW IMAGE>
- (void)clubSelectImage:(XOClubMessageCell *)cell showImage:(UIImage *)image {
    UIScrollView *baseView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight)];
    baseView.backgroundColor = UIColor.blackColor;
    baseView.delegate = self;
    UIImageView *imageView = [[UIImageView alloc]initWithImage:image];
    imageView.center = baseView.center;

    [baseView addSubview:imageView];
    baseView.minimumZoomScale = 0.5;
    baseView.maximumZoomScale = 2.0;

    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action: @selector(tapGesture:)];
    [baseView addGestureRecognizer:tap];
    baseView.alpha = 0.0;

    self.imageView = imageView;
    self.imageBaseView = baseView;

    [[UIApplication sharedApplication].keyWindow addSubview:baseView];
    [UIView animateWithDuration:0.5 animations:^{
        baseView.alpha = 1.0;
    }];
}

- (void)clubClickedComment:(XOClubMessageCell *)cell {
    NSIndexPath *index = [self.tableView indexPathForCell:cell];
    XOClubViewModel* viewModel = [XOClubViewModel shared];
    viewModel.clubMessageModel = self.clubList.list[index.row];
    XOClubCommentViewController * commentVc = [[XOClubCommentViewController alloc]init];
    viewModel.isComment = YES;
    [commentVc setHidesBottomBarWhenPushed:YES];
    [self.navigationController pushViewController:commentVc animated:YES];
    [commentVc setHidesBottomBarWhenPushed:NO];
}

- (void)clubClickedLikeAction:(XOClubMessageCell *)cell likeButton:(XOLikeButton *)button {
    if ([EJSUserModel userModel]) {
        NSIndexPath *index = [self.tableView indexPathForCell:cell];
        EJSClubMessageModel *model = self.clubList.list[index.row];
        self.updateIndexPath = index;
        self.updateLikeButton = button;
        if ([button isSelected]) {
            [button setSelected:NO];
            [button stopButtonAnimation];
            model.loveTotal = [NSString stringWithFormat:@"%d", model.loveTotal.intValue - 1];
            model.hasLoved = @(0);
            [self cancelClubLikeRequest: model];
        }else {
            [button setSelected:YES];
            [button startButtonAnimation];
            model.loveTotal = [NSString stringWithFormat:@"%d", model.loveTotal.intValue + 1];
            model.hasLoved = @(1);
            [self clubLikeRequest:self.clubList.list[index.row]];
        }
    }else {
        [[HUDHelper sharedInstance] tipMessage:@"请先登录"];
    }
}

- (void)clubLikeRequest: (EJSClubMessageModel *)model{
    FlyWeakSelf
    EJSClublikeRequest *request = [EJSClublikeRequest new];
    request.moment_id = model.momentId;
    [request asyncRequestWithsuccessHandler:^(BaseResponse *response) {
        [weakSelf getClubListRequest];
    } failHandler:^(BaseResponse *response) {
        [[HUDHelper sharedInstance] tipMessage:@"无法点赞" delay:1];
        model.loveTotal = [NSString stringWithFormat:@"%d", model.loveTotal.intValue - 1];            [weakSelf.updateLikeButton stopButtonAnimation];
        [weakSelf.updateLikeButton setSelected:NO];
    }];
}

- (void)cancelClubLikeRequest: (EJSClubMessageModel *)model{
    FlyWeakSelf
    EJSClubCancelLikeRequest *request = [EJSClubCancelLikeRequest new];
    request.moment_id = model.momentId;
    [request asyncRequestWithsuccessHandler:^(BaseResponse *response) {
            //            [[HUDHelper sharedInstance]tipMessage:@"成功取消点赞" delay:1.0];
            //            [weakSelf.tableView reloadRowsAtIndexPaths:@[weakSelf.updateIndexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
        [weakSelf getClubListRequest];
    } failHandler:^(BaseResponse *response) {
        [[HUDHelper sharedInstance]tipMessage:@"无法取消点赞" delay:1.0];
        model.loveTotal = [NSString stringWithFormat:@"%d", model.loveTotal.intValue + 1];
        [weakSelf.updateLikeButton setSelected:YES];
    }];
}
/**
 点击手势
 @param tap 点击
 */
-(void) tapGesture: (UITapGestureRecognizer *)tap {
    [self dissmissImageView];
}

/**
 退出图片展示
 */
- (void) dissmissImageView {
    [UIView animateWithDuration:0.5 animations:^{
        self.imageBaseView.alpha = 0.0;
    } completion:^(BOOL finished) {
        [self.imageBaseView removeFromSuperview];
    }];
}

    //MARK: - SCROLLVIEW DELEGATE
- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView {
    return self.imageView;
}
- (void)scrollViewDidZoom:(UIScrollView *)scrollView {
    CGPoint center = scrollView.center;
    center.x = scrollView.contentSize.width > scrollView.frame.size.width ? scrollView.contentSize.width / 2 : center.x;
    center.y = scrollView.contentSize.height > scrollView.frame.size.height ? scrollView.contentSize.height / 2 : center.y;
    self.imageView.center = center;
}

@end
